import { contextBridge, ipcRenderer } from 'electron'
import { electronAPI } from '@electron-toolkit/preload'
import log from 'electron-log'
// 从主进程获取可用 API 清单，避免在 preload 中直接 import 主进程代码
async function buildApiProxy(): Promise<any> {
  const apiModules: Record<string, string[]> = await ipcRenderer.invoke('listApiModules')
  console.log('[Preload] 收到 API 模块:', apiModules)
  const api: any = {}
  for (const [moduleName, methodNames] of Object.entries(apiModules)) {
    api[moduleName] = {}
    for (const methodName of methodNames) {
      api[moduleName][methodName] = (...args: any[]) => {
        const channel = `${moduleName}.${methodName}`
        return ipcRenderer.invoke(channel, ...args)
      }
    }
  }
  return api
}

;(async () => {
  try {
    const api = await buildApiProxy()
    contextBridge.exposeInMainWorld('electron', electronAPI)
    contextBridge.exposeInMainWorld('api', api)
  } catch (error) {
    log.error('[Preload] 生成 API 代理失败:', error)
  }
})()
